import amara

from Ft.Lib import Uri
from paste.request import parse_formvars
from paste.httpexceptions import *

from wsgiappclient.namespaces import *
from wsgiappclient.models.user import User
from wsgiappclient.controllers.base import BaseController
from wsgiappclient.utils import get_session
from wsgiappclient.atompubclient import AtomPubClient



from pprint import pprint

class UserController(BaseController):
    def __init__(self, app, app_conf={}):
        self.app_conf = app_conf
        self.app = app

    def __call__(self, environ, start_response):
        args = environ['wsgiorg.routing_args'][1]
        func = self.dispatch(environ, start_response, 'model')
        if func:
            return func(environ, start_response)
        return self.app(environ, start_response)

    def GET_index(self, environ, start_response):
        self.setup(environ, start_response)
        data = environ.get('wsgiappclient.post_index_data', {})
        errors = environ.get('wsgiappclient.post_index_errors', {})
        data['flash'] = self.sess.get('flash', '')
        self.sess['flash'] = ''
        self.sess.save()
        data['base_url'] = self.app_conf['base_url']
        data['openid'] = self.sess['user_id']
        user_xml = self.user.get_xml_with_collections()
        environ['xsltemplate.template'] = 'index/forms.xslt'
        params = environ.get('xsltemplate.params', {})
        params.update(data)
        start_response('200 OK', [('content-type', 'text/html')])
        return [user_xml]

    def POST_author(self, environ, start_response):
        self.setup(environ, start_response)
        self.user.add_author(self.post)
        self.sess['flash'] = 'Author Updated!'
        self.sess.save();
        return self.get_index(environ, start_response)

    def GET_service(self, environ, start_response):
        self.setup(environ, start_response)
        data = {}
        data['flash'] = self.sess.get('flash', '')
        self.sess['flash'] = ''
        self.sess.save()
        data['base_url'] = self.app_conf['base_url']
        data['openid'] = self.sess['user_id']
        environ['xsltemplate.template'] = 'user/service/forms.xslt'
        params = environ.get('xsltemplate.params', {})
        params.update(data)
        start_response('200 OK', [('content-type', 'text/html')])
        return [self.user.get_xml()]
        
    def POST_service(self, environ, start_response):
        self.setup(environ, start_response)
        result = self.user.get_xml()
        if self.post.get('action'):
            action = self.post['action']
            print "Have action: %s" % action
            if action == 'user-add-collections':
                result = self.user_add_collections()
            if action == 'service-get-collections':
                environ['xsltemplate.params'].update({
                    'service_base_url': self.post['app_service'],
                })
                result = self.service_get_collections()
                print "Service (after return): %s" % result
        environ['xsltemplate.template'] = 'user/service/forms.xslt'
        start_response('200 OK', [('content-type', 'text/html')])
        return [result]

    def user_add_collections(self):
        collection_urls = self.post.getall('collection_urls')
        if not collection_urls:
            self.sess['flash'] = 'No collections were selected'
            return
        message = []
        for c in collection_urls:
            username = self.post.get('username', None)
            password = self.post.get('password', None)
            if c:
                self.user.add_collection(c, username, password)
                self.user.save()
        self.sess['flash'] = 'Added Collections!'
        self.sess.save()
        return self.user.get_xml()

    def service_get_collections(self):
        if not self.post['app_service']:
            return 
        if self.post.get('username') and self.post.get('password'):
            client = AtomPubClient(
                service_url=self.post['app_service'],
                username=self.post['username'],
                password=self.post['password'],
            )
        else:
            client = AtomPubClient(service_url=self.post['app_service'])

        try:
            service = client.load_service_url()
            print "Service: %s" % service
            sdoc = amara.parse(service,
                prefixes=COMMON_PREFIXES
            )
            if sdoc:
                return sdoc.xml()
        except:
            pass

